import os
import time
import urllib
from DrissionPage import Chromium,ChromiumOptions
from DrissionPage._elements.none_element import NoneElement
from urllib.parse import urlparse, parse_qs
import json
from config import redis_config
from cookie import cookie_to_dict
from redis_api import get_redis
redis = get_redis(redis_config)
#邮箱密码
mail = 'beginvpnchannel@gmail.com'
password = 'dEbUg2024@@@'
co= ChromiumOptions()
# prefs = {
#     "printing.print_preview_sticky_settings.appState": '{"recentDestinations":[{"id":"Save as PDF","origin":"local","account":"","capabilities":{}}],"selectedDestinationId":"Save as PDF","version":2}',
#     "savefile.default_directory": "/path/to/save/pdf",  # 设置保存 PDF 的目录
#     "download.prompt_for_download": False,  # 不提示下载
# }
co.set_pref(arg='printing.print_preview_sticky_settings.appState', value='{"recentDestinations":[{"id":"Save as PDF","origin":"local","account":"","capabilities":{}}],"selectedDestinationId":"Save as PDF","version":2}')
co.set_pref(arg='savefile.default_directory', value='C:\\Users\Banana\\PycharmProjects\\booking-auto')
co.set_pref(arg='download.prompt_for_download', value=False)
tab = Chromium(addr_or_opts=co).latest_tab
def get_url_params(url):
    # 解析 URL
    parsed_url = urlparse(url)

    # 获取查询参数并转换为字典
    params_dict = parse_qs(parsed_url.query)

    # 将值转换为字符串（去掉列表）
    params_dict = {k: v[0] for k, v in params_dict.items()}

    return params_dict
def parse_cookies(cookie_string):
    cookies = []
    for cookie in cookie_string.split('; '):
        name, value = cookie.split('=', 1)
        # 每个 cookie 需要 domain 和 path
        cookie_item = {
            'name': name,
            'value': urllib.parse.quote(value),
            'domain': 'secure.booking.com',  # 确保设置正确的域名
            'path': '/',       # 通常设置为根路径
            'httpOnly': True,  # 可选
            'secure': True,    # 可选
            'sameSite': 'Lax'  # 可选
        }
        cookie_item2 = {
            'name': name,
            'value': urllib.parse.quote(value),
            'domain': 'www.booking.com',  # 确保设置正确的域名
            'path': '/',  # 通常设置为根路径
            'httpOnly': True,  # 可选
            'secure': True,  # 可选
            'sameSite': 'Lax'  # 可选
        }
        # if name=='aws-waf-token':
        #     cookie_item['secure'] = True
        #     cookie_item['sameSite'] = 'Lax'
        #
        # if name  in ['bkng_ap_sso_session','bkng','bkng_ap','esadm','bkng_sso_session','bkng_ap_lang','cnfunco_guest','pcm_consent','BJS','bkng_sso_auth','bkng_sso_ses','bkng_sso_ses','FPID']:
        #     cookie_item['secure'] = True
        #     cookie_item['httpOnly'] = True
        #     cookie_item['sameSite'] = 'Lax'
        cookies.append(cookie_item)
        cookies.append(cookie_item2)
    return cookies

application_data = redis.get(f'application_data_{mail}')
application_data = json.loads(application_data)
base_page_url_dict = get_url_params(application_data['basePageUrl'])
label = application_data['affiliate']['label']
key = application_data['affiliate']['label']
sid = base_page_url_dict['sid']
aid = base_page_url_dict['aid']
cookie_string = redis.get(f'cookie_str_{mail}')
cookie_string = str(cookie_string,'utf-8')
cookies = parse_cookies(cookie_string)
auth_key = 'YXCQtLwzAnUqcaYQ'
# 以该配置创建页面对象
target_url = f'https://secure.booking.com/confirmation.en-gb.html?aid={aid}&label={label}&sid={sid}&auth_key={auth_key}'

# 导航到你想打印的网页
tab.get(target_url)

current_url = tab.url
select_al = tab.ele('css=input[name="selectAll"]')
if isinstance(select_al, NoneElement):
    print("元素不存在 (NoneElement)")
else:
    time.sleep(1)
    tab.run_js("document.querySelector('input[name=\"selectAll\"]').click()")
    time.sleep(1)
    tab.wait.ele_displayed('button')
    tab.ele('button').click()

#data-testid="header-sign-in-button"
sign_in_el = tab.ele('css=a[data-testid="header-sign-in-button"]')
# 判断是否登录
if isinstance(sign_in_el, NoneElement):
    print("登录成功")
else:
    # 登录页面
    sign_in_el = 'css=a[data-testid="header-sign-in-button"]'
    tab.wait.ele_displayed(sign_in_el)
    tab.ele(sign_in_el).click()
    # 勾选协议
    r3_el = tab.ele('#:r3:')
    if isinstance(r3_el, NoneElement):
        print("元素不存在 (NoneElement)")
    else:
        tab.ele('#:r3:').click()
        time.sleep(1)
    # 输入账号
    tab.wait.ele_displayed('#username')
    tab.ele('#username').clear()
    tab.ele('#username').input(mail)
    # 提交邮箱
    time.sleep(0.2)
    tab.ele('css=button[type="submit"]').click()
    # # 定位到密码文本框并输入密码
    tab.wait.load_start()
    tab.wait.ele_displayed('css=input[type="password"]')
    tab.ele('css=input[type="password"]').clear()
    tab.ele('css=input[type="password"]').input(password)
    # 点击登录按钮
    tab.ele('css=.nw-signin button[type="submit"]').click()
#等待跳转结束
tab.wait.doc_loaded()
#reservation-status__title reservation-status__title--cancelled
cancelled_el = tab.ele('css=.reservation-status__title--cancelled')
# 判断是否登录
if isinstance(cancelled_el, NoneElement):
    tab.wait.ele_displayed('css=.bui-modal__close')
    tab.ele('css=.bui-modal__close').click()
    # 打印
    tab.run_js(f'document.title="{auth_key}"')
    #js-save-pdf-action
    tab.wait.ele_displayed('css=.js-save-pdf-action')
    tab.ele('css=.js-save-pdf-action').click()

    tab.wait.ele_displayed('css=#js-conf-print-link-user-lang')
    tab.ele('css=#js-conf-print-link-user-lang').click()
    print(tab.url)


    # 等待跳转结束
    tab.wait.doc_loaded()
    time.sleep(10)
    import pyautogui
    import time
    # 模拟按下 Ctrl+P 打开打印预览
    pyautogui.hotkey('ctrl', 'p')
    # 等待对话框加载
    time.sleep(10)
    # 模拟按下 Enter 键确认打印（或选择保存路径）
    pyautogui.press('enter')
    time.sleep(1)
    pyautogui.press('enter')
    time.sleep(1)
    pyautogui.press('enter')
    print('订单取消成功')
    time.sleep(50)
else:
    print('订单已取消')

tab.close()  # 关闭浏览器
